package com.yumeng.framework.persistence.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import com.yumeng.framework.persistence.mybatis.injector.MyAbstractMethod;
import com.yumeng.framework.persistence.mybatis.injector.MySqlMethod;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 逻辑批量删除
 * @author wxd
 * @date 2021/12/14 21:05
 */
public class logicDeleteByIds extends MyAbstractMethod {

    private static final MySqlMethod SQL_METHOD = MySqlMethod.LOGIC_DELETE_BY_IDS;

    public logicDeleteByIds() {
        super(SQL_METHOD.getMethod());
    }

    /**
     * 注入自定义 MappedStatement
     * "<script>\nUPDATE %s %s WHERE %s IN (%s) %s\n</script>"
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        if (!myHasLogicDelete(tableInfo)) return null;
        String sql = myLogicDeleteScript(tableInfo, SQL_METHOD);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
        return addUpdateMappedStatement(mapperClass, modelClass, sqlSource);
    }

    /**
     * 逻辑删除脚本
     * @param tableInfo
     * @param sqlMethod
     * @return
     */
    public String myLogicDeleteScript(TableInfo tableInfo, MySqlMethod sqlMethod) {
        return String.format(sqlMethod.getSql(), tableInfo.getTableName(),
                mySqlLogicSet(tableInfo, null), tableInfo.getKeyColumn(), SqlScriptUtils.convertForeach(
                        SqlScriptUtils.convertChoose("@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(item.getClass())",
                                "#{item}", "#{item." + tableInfo.getKeyProperty() + "}"),
                        getMybatisPlusProperties().getCommKeyProps(), null, "item", COMMA),
                myGetLogicDeleteSql(true, true, null));
    }

}
